<template>
	<view class="create-update">
		
		<view class="tips">此商品已存在？<text class="tips-event" @click="toSearchSelectPage">编辑原有库存</text></view>
		
		<view class="box-card">
			<view class="cell">
				<view class="cell-label">商品图片</view>
				<view class="cell-value">
					<view class="upload-box" hover-class="btn-hover" @click="onUploadCover">
						<image v-if="postForm.picUrl" class="upload-image" :src="postForm.picUrl" mode="aspectFit"></image>
						<view v-else class="upload-btn">
							<image class="upload-icon" src="@/static/icons/up-img.png" mode="aspectFit"></image>
							<text class="upload-text">上传图片</text>
						</view>
					</view>
				</view>
			</view>
			<view class="cell">
				<view class="cell-label">商品号</view>
				<view class="cell-value">
					<u--input 
						v-model="postForm.goodsSn" 
						fontSize="30" 
						border="surround" 
						placeholder="请输入商品号" 
						placeholderClass="contact-inputholder" 
					></u--input>
				</view>
			</view>
			<view class="cell">
				<view class="cell-label">商品名称</view>
				<view class="cell-value">
					<u--input 
						v-model="postForm.name" 
						fontSize="30" 
						border="surround" 
						placeholder="请输入商品名称" 
						placeholderClass="contact-inputholder" 
					></u--input>
				</view>
			</view>
			<view class="cell">
				<view class="cell-label">商品产地</view>
				<view class="cell-value" @click="onToggleProducer">
					<u-input 
						:value="postForm.factoryName" 
						border="surround" 
						readonly 
						fontSize="30" 
						placeholder="请选择商品产地" 
						placeholderClass="contact-inputholder" 
					>
						<view slot="suffix" class="m-l-10">
							<view class="icon-anim" :class="{'icon-run': showProducer}">
								<u-icon name="arrow-right" color="#333" size="24rpx"></u-icon>
							</view>
						</view>
					</u-input>
				</view>
			</view>
		</view>
		
		<view class="box-card m-t-20">
			<view class="product-cell" v-for="(item, index) in postForm.products" :key="item.id">
				<view class="product-cell-label">
					<u--input
						v-model="item.sku" 
						fontSize="30" 
						border="surround" 
						placeholder="输入规格" 
						placeholderClass="contact-inputholder" 
					></u--input>
				</view>
				<view class="product-cell-stock">
					<u--input
						v-model="item.stock" 
						fontSize="30" 
						border="surround" 
						placeholder="库存" 
						placeholderClass="contact-inputholder" 
					></u--input>
				</view>
				<!-- 图片上传 -->
				<view class="product-cell-upload">
					<image 
						v-if="item.pic" 
						:src="item.pic" 
						class="upload-image" 
						mode="aspectFill" 
						@click="onShowSkuPicAction(index)"
					></image>
					<view v-else class="upload-btn" @click="handleUploadSkuPic(index)">
						<image class="upload-icon" src="@/static/icons/up-img-mini.png" mode="aspectFit"></image>
					</view>
				</view>
				<!-- 删除 -->
				<view v-if="postForm.products.length > 1" class="product-cell-del" @click="handleRemoveSku(index)">
					<u-icon name="trash" color="#fff" size="36rpx"></u-icon>
				</view>
			</view>
			<view class="add-btn-wrap">
				<button class="add-btn" type="success" @click="handleAddSku">增加规格</button>
			</view>
		</view>
		
		<view class="p-30" v-if="editPermi">
			<button 
				class="submit-btn" 
				:disabled="submitLoading" 
				@click="handleSubmit"
			>{{ submitText }}</button>
		</view>
		
		<!-- 选择产地 -->
		<u-picker
			:show="showProducer" 
			:columns="[producerOptions]" 
			itemHeight="88" 
			title="选择产地" 
			keyName="dictLabel" 
			closeOnClickOverlay 
			confirmColor="#13a0e7" 
			@close="onToggleProducer" 
			@cancel="onToggleProducer" 
			@confirm="onProducerConfirm"
		></u-picker>
		
		<!-- 规格媒体 -->
		<u-action-sheet 
			:show="showSkuPicAction" 
			:actions="skuPicActions" 
			:round="20" 
			closeOnClickAction 
			closeOnClickOverlay 
			safeAreaInsetBottom 
			cancelText="关闭" 
			@close="showSkuPicAction = false" 
			@select="handleSkuPicActionClick"
		></u-action-sheet>
	</view>
</template>

<script>
	import { deepClone, getUUId } from "@/utils/util.js"
	import { onSingleUploadImage } from "@/utils/upload.js"
	import { stockInfo, stockSave } from '@/api/stock.js'
	import userMixins from '@/mixins/user.js'
	import { PostType, StoreType, SuperFlag } from '@/utils/enum.js'
	
	// 产地
	const producerOptions = ['广州工厂', '呼和浩特工厂']

	// 规格项
	const skuItem = () => {
		return {
			sku: '',
			stock: '',
			pic: '',
		}
	}
	
	const postForm = {
		goodsSn: '',
		name: '',
		picUrl: '',
		factoryName: '',
		products: [skuItem()],
	}
	
	export default {
		mixins: [userMixins],
		props: {
			update: Boolean,
			stockId: [Number, String],
		},
		data() {
			return {
				postForm: deepClone(postForm),
				submitLoading: false,
				
				// 产地
				showProducer: false,
				producerOptions,
				
				// sku
				showSkuPicAction: false,
				skuPicActions: [
					{ name: '预览', value: 'preview' },
					{ name: '上传', value: 'upload' },
				],
			}
		},
		computed: {
			// 总店超管或者总店库管才有编辑权限
			editPermi() {
				return this.userInfo.storeType == StoreType.main && (this.userInfo.superFlag == SuperFlag || this.userInfo.postId == PostType.stock)
			},
			submitText() {
				if (this.update) {
					return this.submitLoading ? '正在更新' : '确定更新'
				} else {
					return this.submitLoading ? '正在录入' : '确定录入'
				}
			}
		},
		watch: {
			staffId() {
				if (this.update) {
					this.getInfo()
				} else {
					this.postForm = deepClone(postForm)
				}
			}
		},
		created() {
			// #ifdef H5
			if (this.update) {
				this.getInfo()
			} else {
				this.postForm = deepClone(postForm)
			}
			// #endif
		},
		methods: {
			// 详情
			async getInfo() {
				const { data } = await stockInfo(this.stockId)
				this.postForm = data
			},
			// 去选择商品进行编辑
			toSearchSelectPage() {
				uni.navigateTo({
					url: '/pages/stock/search-select',
					events: {
						select(data) {
							// 重定向到编辑页面 延迟执行 保证选择后已经返回到当前页
							setTimeout(() => {
								uni.redirectTo({
									url: '/pages/stock/update?stockId=' + data.stockId,
								})
							}, 300)
						}
					}
				})
			},
			// 显示隐藏产地
			onToggleProducer() {
				this.showProducer = !this.showProducer
			},
			// 选择产地
			onProducerConfirm(event) {
				this.postForm.factoryName = event.value[0]
				this.onToggleProducer()
			},
			// 上传图片
			async onUploadCover() {
				const { url } = await onSingleUploadImage()
				this.postForm.picUrl = url
			},
			// 增加规格
			handleAddSku() {
				this.postForm.products.push(skuItem())
			},
			// 删除规格
			handleRemoveSku(index) {
				this.postForm.products.splice(index, 1)
			},
			// 显示操作菜单（预览、上传）
			onShowSkuPicAction(index) {
				this.skuPicActionIndex = index
				this.showSkuPicAction = true
			},
			// 选择操作菜单
			handleSkuPicActionClick(e) {
				const { value } = e
				const skuIndex = this.skuPicActionIndex
				
				if (value === 'upload') {
					this.handleUploadSkuPic(skuIndex)
				} else if (value === 'preview') {
					const { pic } = this.postForm.products[skuIndex]
					uni.previewImage({
						current: pic,
						urls: [pic],
					})
				}
			},
			// 上传规格图
			async handleUploadSkuPic(index) {
				const { url } = await onSingleUploadImage()
				this.postForm.products[index].pic = url
			},
			// 提交保存
			async handleSubmit() {
				try {
					this.onValidate()
					this.submitLoading = true
					await stockSave(this.postForm, this.update)
					if (this.update) {
						this.$emit('submit', this.postForm)
					}
					uni.navigateBack()
				} catch(e) {
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
				} finally {
					this.submitLoading = false
				}
			},
			// 验证
			onValidate() {
				const isEmpty = uni.$u.test.isEmpty
				const postForm = this.postForm
				const throwError = (msg) => {
					throw new Error(msg)
				}
				
				if (isEmpty(postForm.picUrl)) {
					throwError('请上传商品图片')
				}
				if (isEmpty(postForm.goodsSn)) {
					throwError('商品号不能为空')
				}
				if (isEmpty(postForm.name)) {
					throwError('商品名称不能为空')
				}
				if (isEmpty(postForm.factoryName)) {
					throwError('商品产地不能为空')
				}
				if (isEmpty(postForm.products)) {
					throwError('请输入规格')
				}
				const hasEmpty = Object.values(postForm.products).some(item => {
					return item.sku == '' || item.stock == ''
				})
				if (hasEmpty) {
					throwError('请完善规格')
				}
			}
		}
	}
</script>

<style lang="scss">
	.contact-inputholder {
		font-size: 30rpx;
		font-weight: 300;
		line-height: 1.2;
		color: $u-tips-color !important;
	}
</style>

<style lang="scss" scoped>
	.create-update {
		padding: 20rpx;
		.tips {
			font-size: 28rpx;
			font-weight: normal;
			color: #333;
			margin-bottom: 20rpx;
			&-event {
				color: $u-primary;
			}
		}
		.box-card {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 30rpx;
		}
		.cell {
			display: flex;
			align-items: center;
			.cell-label {
				width: 5em;
				font-size: 30rpx;
				font-weight: normal;
				color: #333;
				text-align: right;
			}
			.cell-value {
				flex: 1;
				margin-left: 20rpx;
				.icon-anim {
					transition: transform 0.2s;
					transform: rotate(0deg);
				}
				.icon-anim.icon-run {
					transform: rotate(90deg);
				}
				.upload-box {
					position: relative;
					width: 280rpx;
					height: 160rpx;
					border: 1px solid $u-border-color;
					border-radius: 16rpx;
					overflow: hidden;
					box-sizing: border-box;
					.upload-image {
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
					}
					.upload-btn {
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						.upload-icon {
							width: 88rpx;
							height: 88rpx;
						}
						.upload-text {
							font-weight: 400;
							font-size: 24rpx;
							color: $u-tips-color;
						}
					}
					.upload-btn[disabled] {
						background-color: #eee;
						pointer-events: none;
					}
				}
			}
		}
		.cell + .cell {
			margin-top: 30rpx;
			visibility: visible;
		}
		.product-cell {
			display: flex;
			align-items: center;
			&-label {
				flex: 1;
			}
			&-stock {
				flex: 0.5;
				margin-left: 20rpx;
			}
			&-upload {
				position: relative;
				margin-left: 20rpx;
				width: 70rpx;
				height: 70rpx;
				border: 1px solid #eee;
				border-radius: 8rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				overflow: hidden;
				.upload-btn {
					width: 100%;
					height: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
					.upload-icon {
						width: 44rpx;
						height: 44rpx;
					}
				}
				.upload-image {
					width: 100%;
					height: 100%;
				}
			}
			&-del {
				margin-left: 20rpx;
				width: 70rpx;
				height: 70rpx;
				border-radius: 50%;
				background-color: $u-error;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
		.product-cell + .product-cell {
			margin-top: 20rpx;
		}
		.add-btn-wrap {
			margin-top: 30rpx;
			display: flex;
			justify-content: center;
			.add-btn {
				margin: 0;
				padding: 0;
				background-color: $u-primary;
				width: 200rpx;
				height: 70rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				color: #fff;
				border-radius: 12rpx;
				&::after {
					border: none;
				}
			}
			.add-btn[type="success"] {
				background-color: #07c160;
			}
			.add-btn[disabled] {
				background-color: #c8c9cc;
			}
		}
		.submit-btn {
			margin: 0 auto;
			padding: 0;
			background-color: $u-primary;
			width: 300rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 30rpx;
			color: #fff;
			border-radius: 12rpx;
			&::after {
				border: none;
			}
		}
		.submit-btn[disabled] {
			background-color: #c8c9cc;
		}
	}
</style>